
const dns = require('./aliyun-dns');
const fs  = require('fs-extra')
const  { pushRemote,getEncodeIp } = require('./update-dns')
const http = require('http');
const url = require('url');
const ipPath = `${__dirname}/lucky.json`;


const hostname = '0.0.0.0'
const port = 10001

function updateIp(ip) {
  const encodeIp = getEncodeIp(ip)
  try {
    dns.updateRecordIp(ip).then(() => {
      fs.outputFileSync(ipPath, encodeIp);
      pushRemote(ip)
    });
  } catch (error) {
    console.log(error)
  }

}
const server = http.createServer((req, res) => {
  console.log(`访问的url是：${req.url}`)
  let {query} = url.parse(req.url, true);
  if(!query) return;
  const {ip} = query;
  if(!ip) return;
  res.statusCode = 200
  res.setHeader('Content-Type', 'application/json')
  updateIp(ip)
  res.end(getEncodeIp(ip))
})

server.listen(port, hostname, () => {
  console.log(`please visit http://${hostname}:${port}/`)
})


